//
//  HMComposeViewController.swift
//  WeiBo14
//
//  Created by HM on 16/3/11.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class HMComposeViewController: UIViewController {
    
    // toolBar是否要执行跟随键盘的动画
    lazy var isToolBarAnimation: Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    
    // MARK: - 监听方法
    
    @objc private func keyboardDelDidSelected(){
        // 删除按钮点击要执行的逻辑
        textView.deleteBackward()
    }
    
    /// 发送微博的方法
    @objc private func send(){
        
        if pictureView.images.count > 0 {
            // 发表图片微博
            upload()
        }else{
            // 发表文字微博
            update()
        }
        
//        // 1. 定义url
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
//        // 2. 定义参数
//        let parameters = [
//            "access_token": accessToken,
//            "status": textView.text!
//        ]
//        
//        // 3. 发送请求
//        HMNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
//            if error != nil {
//                print("发表失败\(error)")
//                SVProgressHUD.showErrorWithStatus("发表失败")
//                return
//            }
//            SVProgressHUD.showSuccessWithStatus("发表成功")
//        }
        
    }
    /// 发表图片微博
    private func upload(){
        // 判断 accessToken 是否有值
        
        HMNetworkTools.sharedTools.upload(textView.emoticonText, image: pictureView.images.first!) { (responseObject, error) -> () in
            if error != nil {
                print("发表失败\(error)")
                SVProgressHUD.showErrorWithStatus("发表失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发表成功")
        }
        
//        guard let accessToken = HMUserAccountViewModel.sharedAccountViewModel.accessToken else {
//            print("accessToken不存在")
//            return
//        }
        
//        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
//        
//        let parameters = [
//            "access_token" :accessToken,
//            "status": textView.emoticonText
//        ]
//        
//        let manager = AFHTTPSessionManager()
//        
//        manager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
//            
//            let image = self.pictureView.images.first!
//            let data = UIImagePNGRepresentation(image)!
//            // 拼接图片数据需要的闭包
//            /**
//                - 参数1:name -> 接口里面对应该文件的字段
//                - 参数2:fileName ->
//                - 参数3:mimeType --> 告诉后台我要传给你的文件是什么类型的
//                    - 大类型/小类型
//                    - image/png text/html text/json
//                    - 如果不知道是什么类型的话: application/octet-stream
//            */
//            formdata.appendPartWithFileData(data, name: "pic", fileName: "aabb", mimeType: "application/octet-stream")
//            
//        }, progress: nil, success: { (_, responseObject) -> Void in
//            // 请求成功要回调的闭包
//            SVProgressHUD.showSuccessWithStatus("发表成功")
//        }) { (_, error) -> Void in
//            // 请求失败要回调的闭包
//            SVProgressHUD.showErrorWithStatus("发表失败")
//        }
    }
    
    /// 发表文字微博
    private func update(){
        HMNetworkTools.sharedTools.update(textView.emoticonText) { (responseObject, error) -> () in
            if error != nil {
                print("发表失败\(error)")
                SVProgressHUD.showErrorWithStatus("发表失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发表成功")
        }
    }
    
    /// 表情按钮点击的通过触发的方法
    @objc private func emoticonButtonClick(noti: NSNotification) {
        // 取到表情模型
        let emoticon = noti.userInfo!["emoticon"]! as! HMEmoticon
        // 添加表情到textView里面
        textView.insertEmoticon(emoticon)
        
        // 以下代表抽取到: 
//        // 代表是图片表情
//        if emoticon.type == "0" {
//            // 0. 取到textView现有的属性文字
//            let originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            // 1. 通过表情模型里面的图片名转成表情图片
//            let image = UIImage(named: "\(emoticon.folderName!)/\(emoticon.png!)", inBundle: HMEmoticonTools.sharedTools.emoticonsBundle, compatibleWithTraitCollection: nil)
//            
//            // 2. 将图片添加到 文字附件(NSTextAttachment)
//            let textAttachment = NSTextAttachment()
//            textAttachment.image = image
//            let imageWH = textView.font!.lineHeight
//            // 设置图片大小
//            textAttachment.bounds = CGRectMake(0, -4, imageWH, imageWH)
//            
//            // 3. 将上一步的 NSTextAttachment 添加到 NSAttributedString
//            let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textAttachment))
//            // 指定表情图片对应的属性文字的字体大小
//            attr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, 1))
//            
//            // 4. 让textView显示 NSAttributedString
//            // 取到光标
//            var selectedRange = textView.selectedRange
//            
//            // 把表情图片对应的attr添加到原来已经有的attr里面去
//            // originalAttr.insertAttributedString(attr, atIndex: selectedRange.location)
//            originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
//            textView.attributedText = originalAttr
//            // 将location加1
//            selectedRange.location++
//            // 将选中的长度改成0,以便在用户选中某段字符的时候,输入表情之后还会选中一段字符
//            selectedRange.length = 0
//            textView.selectedRange = selectedRange
//            
//        }else{
//            // 是emoji
//            textView.insertText((emoticon.code! as NSString).emoji())
//        }
        
    }
    
    
    @objc private func keyboardWillChangeFrame(noti: NSNotification) {
        print(noti.userInfo)
        
        if isToolBarAnimation == false {
            return
        }
        
        
        // 1. 取到结束的frame
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).CGRectValue()
        // 2. 取到动画执行的时间
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        
        
        // 3. 先改约束,再执行layoutIfNeeded
        self.composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endFrame.origin.y-SCREENH)
        }
        
        // 4. layoutIfNeeded
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.composeToolBar.layoutIfNeeded()
        }
    }
    
    @objc private func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: - 私有方法
    
    /// 切换键盘
    private func switchKeyboard(){
        
        // 如果当前是系统键盘,就切换成表情键盘
        if textView.inputView == nil {
            // 设置textView.inputView
            textView.inputView = emoticonKeyboard
            composeToolBar.isSystemKeyboard = false
        }else{
            // 当前是表情键盘,就切换成系统键盘
            textView.inputView = nil
            composeToolBar.isSystemKeyboard = true
        }
        
        isToolBarAnimation = false
        // 取消第一响应者,会发送键盘frame改变的通知,由于我们监听过此通知,所以composetoolBar会执行一个0.25秒的往下的动画,而在0.25秒的动画还没有执行完毕的时候,我们又成为了第一响应者,这个时候又发送了一个键盘frame改变的通知,所以就造成抖动,解决方法就是,第一次取消第一响应的时候不需要去执行动画.
        textView.resignFirstResponder()
        

        isToolBarAnimation = true        // 成为第一响应者
        textView.becomeFirstResponder()
        
    }
    
    /// 选择图片
    private func selectedPicture(){
        let vc = UIImagePickerController()
        // 设置成为代理,为了取得点击之后的图片
        vc.delegate = self
        // 1. 判断照相机是否可用
//        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front) {
//            // 指定数据来源的类型
//            vc.sourceType = .Camera
//        }
        
        // UIImagePickerController.isSourceTypeAvailable(.Camera)
        // 设置是否可以编译
        // vc.allowsEditing = true
        
        
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 懒加载控件
    
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        keyboard.frame = CGRect(origin: CGPointZero, size: CGSize(width: SCREENW, height: 216))
        return keyboard
    }()
    
    // 配图视图
    private lazy var pictureView: HMComposePictureView = {
        let pictureView = HMComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        // 准备一份代码
        // 将代码传给 pictureView
        pictureView.selectedPictureClosure = {[weak self] in
            self?.selectedPicture()
        }
        
        return pictureView
    }()
    
    private lazy var composeToolBar: HMComposeToolbar = {
        let toolBar = HMComposeToolbar(frame: CGRectZero)
        // 设置里面按钮点击要执行的逻辑
        toolBar.composeToolBarButtonClick = {[weak self] (type: HMComposeToolbarButtonType) in
            switch type {
            case .Picture:
                // 选择图片
                self?.selectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("加号")
            }
        }
        return toolBar
    }()
    
    private lazy var textView: HMTextView = {
        let textView = HMTextView(frame: CGRectZero, textContainer: nil)
        textView.placeholder = "听说下雨天音乐和辣条更配哟~~听说下雨天音乐和辣条更配哟~~听说下雨天音乐和辣条更配哟~~"
        textView.font = UIFont.systemFontOfSize(15)
        textView.delegate = self
        // 保存垂直方向能够有弹簧效果
        textView.alwaysBounceVertical = true
        // textView.text = "[带着微博去旅行][马上有对象]"
//        textView.keyboardDismissMode = .OnDrag
        return textView
    }()
    
    // 右边
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        // 设置不同状态下文字颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 设置文字
        button.setTitle("发送", forState: UIControlState.Normal)
        // 设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 40, height: 34)
        // 设置不可用
//        button.enabled = false
        return button
    }()
    
    private lazy var titleView: UILabel = {
        let label = UILabel()
        // 指定换行
        label.numberOfLines = 0
        // 文字居中
        label.textAlignment = .Center
        if let screenName = HMUserAccountViewModel.sharedAccountViewModel.account?.screen_name {
            let text = "发微博\n\(screenName)"
            // 初始化一个带有属性的文字
            let attrText = NSMutableAttributedString(string: text)
           //  attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 3))
            // 定义需要设置的属性
            let attrDict = [
                NSForegroundColorAttributeName: UIColor.lightGrayColor(),
                NSFontAttributeName: UIFont.systemFontOfSize(14),
                NSStrokeWidthAttributeName: 2,
                NSStrokeColorAttributeName: UIColor.redColor()
            ]
            // 求出昵称所在的范围
            let range = (text as NSString).rangeOfString(screenName)
            // 添加属性
            attrText.addAttributes(attrDict, range: range)
            // 设置属性文字
            label.attributedText = attrText
        }else {
            label.text = "发微博"
        }
        label.sizeToFit()

        return label
    }()
}

// MARK: - 图片选择的控制器的代理方法
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleToWidth(600)
        // 测试代码.导出图片
        // let data = UIImagePNGRepresentation(scaleImage)!
        // data.writeToFile("/Users/xiele/Desktop/哈哈.png", atomically: true)
        
        // 图片的W: 1800,H:900 --> W:600H:300
        picker.dismissViewControllerAnimated(true, completion: nil)
        // 调用配图控件的addImage的方法就可以了
        pictureView.addImage(scaleImage)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("用户取消,可以在此弹出一个AlertView,在用户点击之后去执行下面这一行代码")
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        // 设置右边按钮的可用状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

// MARK: - 视图初始化的方法
extension HMComposeViewController {
    
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNavigation()
        
        // 1. 添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
        
        // 2. 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(textView.snp_width).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        // 监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: HMEmoticonDidSelectedNotification, object: nil)
        // 监听删除按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDelDidSelected", name: HMKeyboardDelDidSelectedNotification, object: nil)
    }
    
    // 设置导航栏内容
    private func setupNavigation(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
}
